import { defineStore } from 'pinia'
import { computed, ref } from 'vue'
import {User_Info} from '@/types'
import axios from '@/utils/request'
import {set,get,remove} from '@/utils/storage'

export const useUserStore = defineStore('user', () => {
 
  const userInfo = ref<User_Info|null>(null)

  const isLogined = computed(()=>!!userInfo.value)

  const setUser = (user:User_Info)=>{
    userInfo.value = user
  }

  const removeUser = () => {
    userInfo.value = null
    remove('user_token')
  }

  const refreshUserInfo = async () => {
    const token = get('user_token')
    if(token !== null){
      await axios.get('/user').then(res=>{
        userInfo.value = res.data.user
        set('user_token',res.data.user.token)
      })
    }
  }

  return { isLogined,userInfo, setUser, refreshUserInfo,removeUser }
})